import type { EamEquipmentRepair, EamEquipmentRepairAttachment, EamEquipmentRepairPart, EamEquipmentRepairReport } from "@/pages/eam/repair/entity";
import apiClient from "../../apiClient";

export interface PageListReq {
  //维修单号
  code?: string;
  //设备ID
  equipmentId?: number;
  //维修状态
  repairStatus?: string;
  //紧急状态
  urgency?: string;
  //维修责任人
  repairOwner?: number;
  //维修结果
  repairResult?: string;
  //当前页码
  page: number;
  //每页数量
  pageSize: number;
}

export interface PageListRes {
  //总记录数
  total: number;
  //数据列表
  records: EamEquipmentRepair[];
}

const pageList = (data: PageListReq): Promise<PageListRes> =>
  apiClient.post({
    url: "/eam/equipment/repair/pageList",
    data
});
const getInfo = (id: React.Key): Promise<EamEquipmentRepair> =>
  apiClient.get({
    url: `/eam/equipment/repair/${id}`
});

const add = (data: EamEquipmentRepair): Promise<EamEquipmentRepair> =>
  apiClient.post({
    url: "/eam/equipment/repair",
    data
});

const update = (data: EamEquipmentRepair): Promise<EamEquipmentRepair> =>
  apiClient.put({
    url: "/eam/equipment/repair",
    data
});

const startRepair = (id : React.Key): Promise<void> =>
  apiClient.post({
    url: "/eam/equipment/repair/start/" + id,
});


// 保存维修记录
const saveRecord = (data: EamEquipmentRepair): Promise<EamEquipmentRepair> =>
  apiClient.post({
    url: "/eam/equipment/repair/saveRecord",
    data
});

const remove = (ids: React.Key[]): Promise<void> =>
  apiClient.delete({
    url: "/eam/equipment/repair",
    params: {
    ids: ids.join(",")
  }
});

const getAttachments = (id: React.Key): Promise<EamEquipmentRepairAttachment[]> =>
  apiClient.post({
    url: "/eam/repair/attachment/list",
    data: {
      repairId: id
    }
  });

const getParts = (id: React.Key): Promise<EamEquipmentRepairPart[]> =>
  apiClient.post({
    url: "/eam/repair/part/list",
    data: {
      repairId: id
    }
  });

const getReport = (id: React.Key): Promise<EamEquipmentRepairReport> =>
  apiClient.get({
    url: `/eam/repair/report/parent/${id}`
  });

//上传文件
const uploadFile = (file: File) => {
  const formData = new FormData();
  formData.append("file", file);

  return apiClient.post({
    url: "/eam/repair/attachment/upload",
    data: formData,
    headers: {
      // 不要手动设置Content-Type，让浏览器自动处理
      // 浏览器会自动设置正确的Content-Type和boundary
    },
  });
};

// 根据路径删除文件
const deleteFile = (filePath: string): Promise<EamEquipmentRepairReport> =>
  apiClient.delete({
    url: `/eam/repair/attachment/file`,
    params: {
      filePath
    }
  });

export const eamEquipmentRepairService = {
  pageList,
  getInfo,
  add,
  update,
  remove,
  startRepair,
  getReport,
  getAttachments,
  getParts,
  saveRecord,
  uploadFile,
  deleteFile
};

export default eamEquipmentRepairService;